package com.example.test_witns;

import org.junit.Test;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.security.cert.X509Certificate;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class SSLContextTrustAnyHostname {

    @Test
    public void trustAllCerts() throws Exception {
        TrustManager[] trustAllCerts = new TrustManager[]{
            new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
                public void checkClientTrusted(X509Certificate[] certs, String authType) {
                }
                public void checkServerTrusted(X509Certificate[] certs, String authType) {
                }
            }
        };
        
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    }

    @Test
    public void app() throws Exception {
        trustAllCerts();
        try {
            System.out.println("1");
            // 创建 SSL 上下文
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, null, null);

            System.out.println("2");
            // 获取 SSL 套接字工厂
            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            System.out.println("3");
            // 创建 SSL 套接字
            SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket("104.43.113.253", 12345);

            System.out.println("4");
            // 开始 SSL 握手
            sslSocket.startHandshake();

            System.out.println("5");
            // 发送消息到服务端
            PrintWriter out = new PrintWriter(sslSocket.getOutputStream(), true);
            out.println("你好，服务端！");
            out = new PrintWriter(sslSocket.getOutputStream(), true);
            out.println("你好，服务端！");

            // 接收服务端的响应
            BufferedReader in = new BufferedReader(new InputStreamReader(sslSocket.getInputStream()));
            String response = in.readLine();
            System.out.println("服务端响应：" + response);

            // 关闭连接
            in.close();
            out.close();
            sslSocket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}